package com.abocode.smarten.client.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * Description:
 * Define a  {@code ClientChannelInitializer} extends {@link ChannelInitializer}.
 *
 * @author: guanxianfei
 * @date: 2019/7/24
 */
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
    private static final StringDecoder DECODER = new StringDecoder(CharsetUtil.UTF_8);
    private static final NettyClientHandler CLIENT_HANDLER = new NettyClientHandler();

    private String clientMsg;

    public ClientChannelInitializer(String clientMsg) {
        this.clientMsg = clientMsg;
    }

    @Override
    public void initChannel(SocketChannel ch)  {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("info", new ConnectionHandler(clientMsg));
        pipeline.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast("decoder", DECODER);
        pipeline.addLast("handler", CLIENT_HANDLER);
    }

    public NettyClientHandler getClientHandler() {
        return CLIENT_HANDLER;
    }
}
